from turbogears import expose, redirect, flash
from mnemoply._renewed_lib.crud import CRUDController, TableCol

from mnemoply._renewed_model.field import EducationAgreement as model_Agreement,\
                                          StudentNew, Personality, Group, GroupReserve as model_GroupReserve
from mnemoply._renewed_lib.widgets import GroupField, TextField 

from mnemoply.mass_actions import MassAction
from mnemoply.controllers import Report
from mnemoply.utils import objs2ids, format_date
from mnemoply._renewed_lib.validators import tg_validators, EqualAccountFromTwoPersonalities, NoSamePlan
from mnemoply._renewed_lib.actions import Action, ParamsColumn
from mnemoply.model import field as field_old

class StudentTransfer(Action):
    columns = [ ParamsColumn('group',
                             getter =  lambda(row): row.group.id,
                             widget = GroupField,
                             params={'not_empty':True}
                             ),
               ]
    name = 'student_transfer'#FirstDiscont

    def check_all(self,rows, objs):
        errors = {}
        for row, obj in zip(rows, objs):
            group = field_old.Group.get(row.group)
            some_groups = [1 for r in rows if row.group==group.id]
            count_after = group.cacheStudents - len(some_groups)
            if count_after>group.maxStudents:
                errors["errors_%s"%obj.id] = 'max student'
        
        return errors
    
    def check_one(self, row, obj):
        group = field_old.Group.get(row.group)
        student = obj.student
        plan = group.initialPlan
        agrs= model_Agreement.selectBy(student=student)
        plans = [agr.group.initialPlan for agr in agrs  if agr.group.initialPlan==plan]
        print plans
        if group == obj.group.id:
            return 'no transfer'
        if plans:
            return '1111'
        
        return ''
    
    def apply_one(self, row, obj):
        if obj.id%2:
            obj.group = row.grou
        obj.group = row.group
        return True
    
    
class GroupReserveController(CRUDController):
   # actions = [StudentTransfer()]
    controller_name='GroupReserve'
    model_object = model_GroupReserve
    mysql_view_name = 'prod_v2.group_reserve_lookup'
    lookup_columns = [
        TableCol(name='ed_group', caption=_('Group')),
        TableCol(name='student', caption=_('Student')),
        TableCol(name='customer', caption=_('Customer')),
        TableCol(name='date_enter', caption=_('Date enter'),hidden=True),
        TableCol(name='account', caption=_('Account'), hidden=True),
        TableCol(name='came_from', caption=_('Came from'), hidden=True),
        TableCol(name='school_form', caption=_('Form'), hidden=True),
        TableCol(name='phones', caption=_('Phones'), hidden=True),
        TableCol(name='comment', caption=_('Comment'), hidden=True),
   ]
   # filter_by_user = ['office', 'faculty']

    view_fields = [
        'studentID',
        'customerID',
        'groupID',
        'discontID',
        'cameFromID',
       # 'prefered_day',
        'dateEnter' ,
        'comment'
        ]
    edit_fields = [
        'studentID',
        'customerID',
  #      'groupID',
        'discontID',
        'cameFromID',
       # 'prefered_day',
        'dateEnter' ,
        'comment'
]
    add_fields = [
        'studentID',
        'customerID',
        'groupID',
        'discontID',
       # 'cameFromID',
       # 'prefered_day',
        'dateEnter' ,
        'comment'
        
    ]
    
    chained_validators_edit=[EqualAccountFromTwoPersonalities('customerID', 'studentID'),]
    chained_validators_add=[EqualAccountFromTwoPersonalities('customerID', 'studentID'),('groupID','studentID')]

    def before_update_add(self, data):
        
        customer = Personality.get(int(data['customerID']))
        data['accountID']=customer.account.id
        student = StudentNew.get(int (data['studentID']))
        all_agr =  list(model_Agreement.selectBy(student=student))
        if not data.has_key('cameFromID') or not data['cameFromID']:
            group=Group.get(int(data['groupID']))
            trend=group.initialPlan.trend
            year = group.initialPlan.year
            prev = False
            migr = False
            if all_agr:
                plan = [agr.group.initialPlan for agr in all_agr]
                for pl in plan:
                    if pl.year<year:
                        prev=True
                        if pl.trend == trend and pl.year+1==year:
                            migr = True
                            break
            data['cameFromID'] = 2 # new student
            if prev:
                data['cameFromID'] = 3 # our student
            if migr:
                data['cameFromID'] = 1 # migration
                
        if not all_agr:
            student.academic_year_admission = group.initialPlan.year
        return CRUDController.before_update(self, data)

    def redirect_after(self, came_from=None, obj=None):
        if not obj:
            return '/GroupReserve'
        student = StudentNew.get(obj.student.id)

        is_correct = student.isStudent \
                    and student.student_typeID \
                    and student.birthday\
                    and student.academic_year_admission

        if student.student_typeID ==2:
            is_correct = is_correct \
                         and student.school_name \
                         and student.school_form 
        
            
        if not is_correct:
            return "/Student_new/%s/edit_req"%student.id
        return '/GroupReserve'
    
    

class MAPrint(MassAction):
    target_class = model_Agreement
    name = "agreement_new_print"
    title = _("Print")
    read_only = True
    
    def call(self, objs):
        for obj in objs:
            obj.printCount+=1
        return Report.generate('NewAgreementPrint',
            ids=objs2ids(objs),
            )


class CurrentAgreementController(CRUDController):
    controller_name='EducationAgreement'
  
    mysql_view_name = 'prod_v2.education_agreement_lookup'
    model_object = model_Agreement
    lookup_columns = [
        TableCol(name='ed_group', caption=_('Group')),
        TableCol(name='student', caption=_('Student')),
        TableCol(name='customer', caption=_('Customer')),
        TableCol(name = 'date_creation',caption=_("Payment date")),
        TableCol(name='account', caption=_('Account'), hidden=True),
        TableCol(name = 'amount_reserve',caption=_("Reserve"), hidden=True),
        TableCol(name='came_from', caption=_('Came from'), hidden=True),
        TableCol(name='school_form', caption=_('Form'), hidden=True),
        TableCol(name='phones', caption=_('Phones'), hidden=True),
        TableCol(name='comment', caption=_('Comment'), hidden=True),
    #TableCol(name = 'date_begin',caption=_("Start date")),
    #TableCol(name = 'date_end' ,caption=_("End date")),
    #TableCol(name = 'date_cancellation',caption=_("Cancellation date")),
    ]
    view_fields =[
        'accountID',
        'studentID',
        'customerID',
        'groupID',
        'dateEnter' ,
        'cameFromID',
        'discontID',
        'dateCreation',
        'amount_reserve',
        'comment'
  #     'printCount',
    ]
    edit_fields= []# ['printCount']
    add_fields = []
    @expose()
    def delete(self, obj):
        if not obj.printCount:
            return CRUDController.delete(self, obj)
        flash(_('Record "%s" not deleted!') % obj.title)
        raise redirect("../")
    delete.expose_object = True
class ExpiredAgreementController(CRUDController):
    controller_name='ExpAgreement'
  
    mysql_view_name = 'prod_v2.expired_agreement_lookup'
    model_object = model_Agreement
    lookup_columns = [
    TableCol(name='student', caption=_('Student')),
    TableCol(name='customer', caption=_('Customer')),
    TableCol(name='ed_group', caption=_('Group')),
    TableCol(name = 'account',caption=_("Account")),
    #TableCol(name = 'date_begin',caption=_("Start date")),
    #TableCol(name = 'date_end' ,caption=_("End date")),
    TableCol(name = 'date_cancellation',caption=_("Cancellation date")),
    ]
    is_deleteable = False
    view_fields =[
        'accountID',
        'studentID',
        'customerID',
        'groupID',
        'dateEnter' ,
        'cameFromID',
        'discontID',
        'dateCreation',
        'amount_reserve',
        'comment'
  #     'printCount',
    ]
    edit_fields= []
    add_fields = []

exposed_list = [CurrentAgreementController(),
                GroupReserveController(),
                ExpiredAgreementController()
                ]